package com.zlw.rabbitmq.message;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * @author Zhaoluowei
 * @version 1.0
 * @date 2019/12/22 10:37
 */
public class MessageConsumer {


    public static void main(String[] args) throws IOException, TimeoutException, InterruptedException {

        //1.创建连接工厂
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setVirtualHost("/");
        connectionFactory.setHost("39.100.250.122");
        connectionFactory.setPort(5672);
        connectionFactory.setUsername("guest");
        connectionFactory.setPassword("guest");


        //2. 通过连接工厂 创建连接。
        Connection connection = connectionFactory.newConnection();

        //3. 通过connection 创建channel
        Channel channel = connection.createChannel();

        //4. 创建一个队列。
        /**
         * 第三个参数是否独占 保证消息顺序消费。
         */
        String queueName = "test001";
        channel.queueDeclare(queueName, true, false, false, null);

        //5. 创建消费者 rabbitmq 高版本好像没有这个 方法
        QueueingConsumer consumer = new QueueingConsumer(channel);
        //6. 设置消费者
        channel.basicConsume(queueName, true, consumer);

        //7. 接收消息
        while (true) {
            QueueingConsumer.Delivery delivery = consumer.nextDelivery();
            String msg = new String(delivery.getBody());
            System.out.println("message 消费端 : --> " + msg);


            Envelope envelope = delivery.getEnvelope();
            String correlationId = delivery.getProperties().getCorrelationId();
            String replyTo = delivery.getProperties().getReplyTo();
            String expiration = delivery.getProperties().getExpiration();
            String messageId = delivery.getProperties().getMessageId();


            //收到签收 或者 自动签收
            System.out.println("topic replyTo " + replyTo);
            System.out.println("topic expiration " + expiration);
            System.out.println("topic messageId " + messageId);
            System.out.println("topic correlationId " + correlationId);
            System.out.println("topic 消息的唯一id " + envelope.getDeliveryTag());
            System.out.println("================================================");




        }


    }


}
